<template>
    <div class="main-container">
        <el-row :gutter="20">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <el-card class="card" shadow="never">
                    <div slot="header">
                        <span class="tips">查询条件</span>
                        <div class="right">
                            <el-button icon="el-icon-search" type="primary" @click="queryData">
                                查询
                            </el-button>
                            <el-button icon="el-icon-refresh-left" @click="resetClick">
                                重置
                            </el-button>
                        </div>
                    </div>
                    <el-form label-width="100px">
                        <el-row :gutter="20">
                            <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
                                <el-form-item label="部门名称">
                                    <el-select class="main-select-tree w" ref="selectTree" v-model="queryForm.deptName"
                                               clearable @clear="queryForm.dept_id = ''">
                                        <el-option v-for="item in deptDatas" :key="item.id" :label="item.name"
                                            :value="item.id" style="display: none;" />
                                        <el-tree class="main-select-el-tree" ref="selecteltree" :data="deptDatas"
                                            node-key="id" @node-click="handleNodeClick" highlight-current
                                            :props="defaultProps" :current-node-key="queryForm.dept_id"
                                            :expand-on-click-node="expandOnClickNode" default-expand-all />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
                                <el-form-item label="警号">
                                    <el-input v-model.trim="queryForm.user_name" placeholder="请输入警号" clearable
                                        @keyup.enter.native="queryData" />
                                </el-form-item>
                            </el-col>
                            <!--<el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">-->
                            <!--<el-form-item label="通知权限">-->
                            <!--<el-select v-model="queryForm.username" placeholder="请选择通知权限" class="w">-->
                            <!--<el-option label="110电话报警" value="1"></el-option>-->
                            <!--<el-option label="120电话报警" value="2"></el-option>-->
                            <!--<el-option label="119电话报警" value="3"></el-option>-->
                            <!--</el-select>-->
                            <!--</el-form-item>-->
                            <!--</el-col>-->

                        </el-row>

                    </el-form>
                </el-card>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <el-card class="card" shadow="never">
                    <div slot="header">
                        <span class="tips">用户列表</span>
                        <el-link type="danger" :underline="false" icon="el-icon-warning" style="margin-right: 85px;">重置密码为Jk0516</el-link>
                        <el-button type="success" class="right" icon="el-icon-plus" @click="handleEdit">新增</el-button>
                    </div>
                    <el-table v-loading="listLoading" :data="list" border :element-loading-text="elementLoadingText"
                        @selection-change="setSelectRows" height="calc(100vh - 470px)">
                        <template slot="empty">
                            <el-empty :image-size="200"></el-empty>
                        </template>
                        <el-table-column show-overflow-tooltip label="序号" align="center" width="50px;">
                            <template slot-scope="scope">
                                {{(queryForm.pageNo - 1) * queryForm.pageSize + scope.$index + 1}}
                            </template>
                        </el-table-column>
                        <el-table-column show-overflow-tooltip prop="user_name" label="警号" align="center"></el-table-column>
                        <el-table-column show-overflow-tooltip prop="name" label="姓名" align="center"></el-table-column>
                        <el-table-column show-overflow-tooltip label="部门" prop="deptName" align="center"></el-table-column>
                        <el-table-column show-overflow-tooltip label="手机号码" prop="phone" align="center"></el-table-column>
                        <el-table-column show-overflow-tooltip label="角色" prop="roleNames" align="center"></el-table-column>
                        <el-table-column show-overflow-tooltip label="操作" width="240" align="center">
                            <template #default="{ row }">
                                <el-button size="mini" plain type="primary" @click="resetPass(row)">重置密码</el-button>
                                <el-button size="mini" plain type="primary" @click="handleEdit(row)">编辑</el-button>
                                <el-button size="mini" plain type="danger" @click="handleDelete(row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-pagination background :current-page="queryForm.pageNo" :page-size="queryForm.pageSize"
                        :layout="layout" :total="total" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange2"></el-pagination>
                </el-card>
            </el-col>
        </el-row>
        <edit ref="edit" @fetch-data="fetchData"></edit>
    </div>
</template>

<script>
import {getList, doDelete, resetPassword} from '@/api/userManagement'
import { getDeptList } from '@/api/dept'
import Edit from './components/UserManagementEdit'

export default {
    name: 'UserManagement',
    components: { Edit },
    data() {
        return {
            list: null,
            listLoading: true,
            layout: 'total, sizes, prev, pager, next, jumper',
            total: 0,
            selectRows: '',
            elementLoadingText: '正在加载...',
            queryForm: {
                pageNo: 1,
                pageSize: 10,
                user_name: '',
                dept_id: '',
                deptName: '',
            },
            expandOnClickNode: true,
            options: [],
            deptDatas: [],
            defaultProps: {
                children: 'children',
                name: 'name'
            }
        }
    },
    created() {
        this.fetchData()
        this.getDeptData()
    },
    methods: {
        setSelectRows(val) {
            this.selectRows = val
        },
        // 四级菜单
        async formatData(data) {
            // console.log("部门tree：")
            // console.log(data)
            let options = [];
            data.forEach((item, key) => {
                options.push({ label: item.label, value: item.id });
                if (item.children) {
                    item.children.forEach((items, keys) => {
                        options.push({ label: items.label, value: items.id });
                        if (items.children) {
                            items.children.forEach((itemss, keyss) => {
                                options.push({ label: itemss.label, value: itemss.id });
                                if (itemss.children) {
                                    itemss.children.forEach((itemsss, keysss) => {
                                        options.push({ label: itemsss.label, value: itemsss.id });
                                    });
                                }
                            });
                        }
                    });
                }
            });
            return options;
        },
        handleNodeClick(node) {
            // console.log(node.id)
            this.$set(this.queryForm, "dept_id", node.id);
            this.$set(this.queryForm, "deptName", node.name);
            // this.queryForm.dept_id = node.id;
            this.$refs.selectTree.blur();
        },
        handleEdit(row) {
            if (row.id) {
                this.$refs['edit'].showEdit(row.id)
            } else {
                this.$refs['edit'].showEdit()
            }
        },
        handleDelete(row) {
            if (row.id) {
                this.$baseConfirm('你确定要删除当前项吗', null, async () => {
                    const { msg } = await doDelete(row.id)
                    this.$baseMessage('删除成功', 'success')
                  // 为了在删除最后一页的最后一条数据时能成功跳转回最后一页的上一页
                  const totalPage = Math.ceil((this.total - 1) / this.queryForm.pageSize) // 总页数
                  this.queryForm.pageNo = this.queryForm.pageNo > totalPage ? totalPage : this.queryForm.pageNo
                  this.queryForm.pageNo = this.queryForm.pageNo < 1 ? 1 : this.queryForm.pageNo

                    this.fetchData()
                })
            } else {
                if (this.selectRows.length > 0) {
                    const ids = this.selectRows.map((item) => item.id).join()
                    this.$baseConfirm('你确定要删除选中项吗', null, async () => {
                        const { msg } = await doDelete({ ids })
                        this.$baseMessage(msg, 'success')
                        this.fetchData()
                    })
                } else {
                    this.$baseMessage('未选中任何行', 'error')
                    return false
                }
            }
        },
        handleSizeChange(val) {
            this.queryForm.pageSize = val
            this.fetchData()
        },
        handleCurrentChange2(val) {
            this.queryForm.pageNo = val
            this.fetchData()
        },
        resetClick() {//重置
            this.queryForm = this.$options.data().queryForm;
            // this.queryForm.user_name = '';
            // this.queryForm.dept_id =  '';
            // this.queryForm.deptName = '';
            this.fetchData()

        },
        queryData() {
            this.queryForm.pageNo = 1
            this.fetchData()
        },
        async fetchData() {
            this.listLoading = true
            const { data } = await getList(this.queryForm)
            console.log('用户列表',data.list)
            this.list = data.list
            this.total = data.total
            setTimeout(() => {
                this.listLoading = false
            }, 300)
        },
        getDeptData() {
            getDeptList().then((res) => {
                this.deptDatas = res.data
            })
            // const {data} = await getDeptList()
            // console.log("部门data：")
            // console.log(data)
            // this.deptDatas = data;
        },
        resetPass(row) {
          if (row){
            this.$baseConfirm('你确定要重置此用户密码吗', null, async () => {
              resetPassword(row).then((res) => {
                if (res.code === 0){
                  this.$baseMessage('重置密码成功', 'success')
                }else {
                  this.$baseMessage('重置密码失败', 'error')
                }
              })
            })

          }
        }
    },
}
</script>
